package com.xishu.task;

import com.xishu.client.EmailClient;
import com.xishu.config.Constant;
import com.xishu.dao.jpa.DiscountTicketDao;
import com.xishu.entity.User;
import com.xishu.entity.customer.MarketTask;
import com.xishu.entity.plat.GlobalSetting;
import com.xishu.entity.shop.DiscountTicket;
import com.xishu.service.*;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xishu.config.Constant.MARKET_TASK_STATUS_STOP;

@Api(description = "优惠券模板按时过期")
@Component
public class DiscountTicketExpiredTask implements Tools {
    private static Logger logger = LoggerFactory.getLogger(DiscountTicketExpiredTask.class);
    private CommonService commonService = CommonService.getInstance();

    @Autowired
    private DiscountTicketDao discountTicketDao;

    /**
     * 凌晨一点执行
     */
    @Scheduled(cron = "0 0 0 * * ?")
    private void scanDiscountTicket() {
        Long currentTimeMillis = System.currentTimeMillis();
        logger.info("start deal discountTicket set expire at {}", currentTimeMillis);
        logger.info("currentTime is {}", currentTimeMillis);
        List<DiscountTicket> expiredDiscountTicket = discountTicketDao.expireTicket(currentTimeMillis);

        logger.info("expiredT count is {}", expiredDiscountTicket.size());
        //查出过期的优惠券模板，设置成过期
        for (DiscountTicket discountTicketInDb : expiredDiscountTicket) {
            try {
                discountTicketInDb.setExpired(true);
                commonService.save(discountTicketInDb);
                logger.info("set discountTicket {} to expired", discountTicketInDb.getId());

                //同时查出有哪些还在进行中的营销任务使用了这些优惠券，关闭任务并给管理员发邮件提醒
                MarketTask marketTask = new MarketTask();

                marketTask.setCompanyId(discountTicketInDb.getCompanyId());
                List<MarketTask> marketTaskList = commonService.searchAll(marketTask);

                //过滤出使用了该优惠券的营销任务,已经停止的就不再处理
                List<MarketTask> expiredMarketTask = marketTaskList.stream().filter(s -> {
                    return getList(s.getTicketAndLimitList()).stream().map(p -> {
                        return p.getTicketId();
                    }).collect(Collectors.toList()).contains(discountTicketInDb.getId()) && !equals(s.getStatus(), 1);
                }).collect(Collectors.toList());

                logger.info("expired marketTask count is {}", expiredMarketTask.size());
                for (MarketTask task : expiredMarketTask) {
                    //设置成停止状态
                    task.setStatus(MARKET_TASK_STATUS_STOP);
                    logger.info("stop marketTask {}", task.getId());
                    commonService.save(task);

                    List<DiscountTicket> templateTicketList = getList(task.getTicketAndLimitList()).stream().map(p -> {
                        try {
                            return DiscountTicketService.getInstance().findTicket(p.getTicketId());
                        } catch (Exception e) {
                            return null;
                        }
                    }).filter(p -> p != null).collect(Collectors.toList());

                    List<DiscountTicket> expiredDiscounTicketList = templateTicketList.stream().filter(p -> {
                        return p.getExpired() == true;
                    }).collect(Collectors.toList());

                    if (isNotEmpty(expiredDiscounTicketList)) {
                        //准备邮件内容
                        String taskName_en = "[" + task.getTaskName_en() + "]";
                        String taskName_zh = "[" + task.getTaskName_zh() + "]";
                        List<String> nameList_zh = new ArrayList<>();
                        List<String> nameList_en = new ArrayList<>();
                        for (DiscountTicket discountTicket : expiredDiscounTicketList) {
                            nameList_zh.add(discountTicket.getName_zh());
                            nameList_en.add(discountTicket.getName_en());
                        }

                        String ticketNameList_zh = "[" + StringUtils.join(nameList_zh, ",") + "]";
                        String ticketNameList_en = "[" + StringUtils.join(nameList_en, ",") + "]";

                        GlobalSetting globalSetting = GlobalService.getInstance().getGlobalSetting();
                        String address = globalSetting.getAddress();
                        String city = globalSetting.getCity();
                        String companyWebsite = globalSetting.getCompanyWebsite();
                        String emailAddress = globalSetting.getEmailAddress();

                        String logoUrl = PlatService.getInstance().getLogoUrl();
                        logger.info("logo url is {}", logoUrl);

                        User companyUser = UserService.getInstance().findCompanyUser(task.getCompanyId());

                        String companyUserName = companyUser.getName();

                        //给管理员用户发邮件提示
                        String title = "[DoLA] Your marketing has been stopped. 營銷自動停止。";

                        String email = companyUser.getEmail();

                        String content = String.format("<!DOCTYPE html>\n" +
                                "<html lang=\"en\">\n" +
                                "<head>\n" +
                                "    <meta charset=\"UTF-8\">\n" +
                                "    <title>Title</title>\n" +
                                "</head>\n" +
                                "<body>\n" +
                                "<div style=\"padding-right: 10%%\" align=\"right\"><img style=\"width: 100px;height: 100px;\" src=\"%s\"></div>\n" +
                                "<div style=\"padding-left: 10%%\">\n" +
                                "    <div>Hi %s,</div>\n" +
                                "    <div>Since your coupon %s is expired, your marketing %s has been stopped automatically.</div>\n" +
                                "    <br>\n" +
                                "\n" +
                                "    <div>您好 %s，</div>\n" +
                                "    <div>鑑於您的優惠券%s已過期，因此您的營銷%s自動停止了。</div>\n" +
                                "    <br/>\n" +
                                "    <br/>\n" +
                                "    <br/>\n" +
                                "    <div>If you are not using DoLA, please ignore this email. 如果您并沒有注冊DoLA，請忽略這封電郵。</div>\n" +
                                "</div>\n" +
                                "\n" +
                                "<br/>\n" +
                                "<br/>\n" +
                                "\n" +
                                "<div align=\"center\">\n" +
                                "    <div style=\"color: #808080\">" + address + "<br/>\n" +
                                "        " + city + "<br/>\n" +
                                "    </div>\n" +
                                "    <div style=\"color: #4793A3;text-decoration: none !important;\">" + emailAddress + " | " + companyWebsite + "</div>\n" +
                                "</div>\n" +
                                "</body>\n" +
                                "</html>", logoUrl, companyUserName, ticketNameList_en, taskName_en, companyUserName, ticketNameList_zh, taskName_zh);

                        EmailClient.getInstance().sendEmail(email, title, content);
                    }

                }
            } catch (Exception e) {
                logger.error("e", e);
            }

        }

        logger.info("finish deal ticket to expire at {}", System.currentTimeMillis());
    }

}
